import time
import timeit
import cProfile
import pstats
import os
import sys
from memory_profiler import profile
import psutil
import threading

def get_memory_usage():
    """获取当前内存使用情况"""
    process = psutil.Process(os.getpid())
    return process.memory_info().rss / 1024 / 1024  # 转换为MB

class PerformanceTester:
    def __init__(self):
        self.test_files = {
            'small': 'test_small.py',
            'medium': 'test.py',
            'large': 'test_large.py'
        }
        self.create_test_files()
    
    def create_test_files(self):
        """创建不同大小的测试文件"""
        # 小文件
        small_content = '''
# 小测试文件
def hello():
    """文档字符串"""
    print("hello")  # 注释
    return True
'''
        # 中文件 (使用现有的test.py)
        # 大文件
        large_content = '''# 大型Python测试文件
'''
        # 添加大量代码
        for i in range(500):
            large_content += f'''
class TestClass{i}:
    """类 {i} 的文档字符串"""
    
    def __init__(self):
        self.value = {i}
    
    def method_{i}(self):
        """方法 {i}"""
        # 方法注释
        return self.value * 2
'''
        
        with open('test_small.py', 'w', encoding='utf-8') as f:
            f.write(small_content)
        
        with open('test_large.py', 'w', encoding='utf-8') as f:
            f.write(large_content)
    
    def cleanup(self):
        """清理测试文件"""
        for file in ['test_small.py', 'test_large.py']:
            if os.path.exists(file):
                os.remove(file)
    
    def test_execution_time(self):
        """测试执行时间"""
        print("=== 执行时间测试 ===\n")
        
        # 导入被测试的函数
        sys.path.append('.')
        from wcplus import count_characters, count_words, count_sentences, count_code_lines
        
        results = []
        
        for size, filename in self.test_files.items():
            if os.path.exists(filename):
                print(f"测试文件: {filename} ({size})")
                
                with open(filename, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                # 测试每个函数
                tests = [
                    ('字符统计', lambda: count_characters(content)),
                    ('单词统计', lambda: count_words(content)),
                    ('句子统计', lambda: count_sentences(content)),
                    ('代码统计', lambda: count_code_lines(content, filename))
                ]
                
                for test_name, test_func in tests:
                    # 预热
                    test_func()
                    
                    # 正式测试
                    start_time = time.perf_counter()
                    result = test_func()
                    end_time = time.perf_counter()
                    
                    execution_time = (end_time - start_time) * 1000  # 转换为毫秒
                    results.append((size, test_name, execution_time, result))
                    
                    print(f"  {test_name}: {execution_time:.3f}ms")
                
                print()
        
        return results
    
    @profile
    def test_memory_usage(self):
        """测试内存使用情况"""
        print("=== 内存使用测试 ===\n")
        
        from wcplus import count_characters, count_words, count_code_lines
        
        initial_memory = get_memory_usage()
        print(f"初始内存使用: {initial_memory:.2f} MB")
        
        with open('test_large.py', 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 测试内存使用
        memory_before = get_memory_usage()
        
        chars = count_characters(content)
        words = count_words(content)
        total, code, comment, blank = count_code_lines(content, 'test_large.py')
        
        memory_after = get_memory_usage()
        memory_increase = memory_after - memory_before
        
        print(f"处理前内存: {memory_before:.2f} MB")
        print(f"处理后内存: {memory_after:.2f} MB")
        print(f"内存增加: {memory_increase:.2f} MB")
        print(f"字符数: {chars}, 单词数: {words}")
        print(f"代码行: {total} (代码: {code}, 注释: {comment}, 空行: {blank})")
        
        return memory_increase
    
    def test_concurrent_performance(self):
        """测试并发性能"""
        print("=== 并发性能测试 ===\n")
        
        def worker(worker_id, results):
            start_time = time.perf_counter()
            os.system(f'python wcplus.py -c test.py > nul 2>&1')
            os.system(f'python wcplus.py -w test.py > nul 2>&1')
            end_time = time.perf_counter()
            results[worker_id] = end_time - start_time

    
    def run_comprehensive_test(self):
        """运行全面性能测试"""
        print("🚀 wcplus 性能测试套件")
        print("=" * 50)
        
        try:
            # 执行时间测试
            time_results = self.test_execution_time()
            
            # 内存使用测试
            memory_increase = self.test_memory_usage()
            
            # 生成报告
            self.generate_report(time_results, memory_increase)
            
        finally:
            # 清理测试文件
            self.cleanup()
    
    def generate_report(self, time_results, memory_increase):
        """生成性能测试报告"""
        print("\n" + "=" * 50)
        print("📊 性能测试报告")
        print("=" * 50)
        
        print("\n📈 执行时间排名:")
        sorted_results = sorted(time_results, key=lambda x: x[2])
        for size, test_name, time_ms, result in sorted_results:
            print(f"  {test_name} ({size}): {time_ms:6.3f}ms")
        
        print(f"\n💾 内存使用:")
        print(f"  处理大文件内存增加: {memory_increase:.2f} MB")
        
        print(f"\n📋 性能评价:")
        if all(time_ms < 10 for _, _, time_ms, _ in time_results):
            print("  ✅ 性能优秀 - 所有操作都在10ms以内")
        elif all(time_ms < 50 for _, _, time_ms, _ in time_results):
            print("  ⚠️  性能良好 - 部分操作较慢但可接受")
        else:
            print("  ❌ 性能需要优化 - 存在较慢的操作")
        
        if memory_increase < 10:
            print("  ✅ 内存使用优秀 - 内存增长控制在10MB以内")
        elif memory_increase < 50:
            print("  ⚠️  内存使用良好 - 内存增长在可接受范围")
        else:
            print("  ❌ 内存使用需要优化 - 内存增长过多")

def main():
    tester = PerformanceTester()
    tester.run_comprehensive_test()

if __name__ == "__main__":
    main()